package com.purchase.order.controller;

import cn.com.flaginfo.sdk.cmc.api.request.ApiConfig;
import cn.com.flaginfo.sdk.cmc.api.result.ComResult;
import cn.com.flaginfo.sdk.cmc.api.sms.dynsend.DynSMSSendDataResult;
import cn.com.flaginfo.sdk.cmc.api.sms.dynsend.DynSMSSendRequest;
import com.purchase.common.annotation.Log;
import com.purchase.common.api.SDKApi;
import com.purchase.common.core.controller.BaseController;
import com.purchase.common.core.domain.AjaxResult;
import com.purchase.common.core.page.TableDataInfo;
import com.purchase.common.enums.BusinessType;
import com.purchase.common.exception.file.InvalidExtensionException;
import com.purchase.manage.damian.OrderList;
import com.purchase.manage.damian.StoreQuotation;
import com.purchase.manage.damian.SysSupplierState;
import com.purchase.manage.damian.VO.OrderAllQuotationVO;
import com.purchase.manage.damian.VO.OrderQuotationVO;
import com.purchase.manage.damian.VO.OrderVO;
import com.purchase.order.domain.DAO.OrderDAO;
import com.purchase.order.mapper.OrderMapper;
import com.purchase.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.testng.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.ServerException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.purchase.common.utils.http.HttpClientUtil.sendPostByForm;


@RestController
@RequestMapping("/order")
public class OrderController extends BaseController {

    @Autowired
    IOrderService orderService;

    @Autowired
    OrderMapper orderMapper;


    @Log(title = "采购员查看发布的订单", businessType = BusinessType.SELECT)
    @GetMapping("/release")
    public TableDataInfo releaseList(String type, Long orderId, String materialTypeName) {
        startPage();
        List<OrderDAO> list = orderService.selectreleaseList(type, orderId, materialTypeName);
        return getDataTable(list);
    }

    @Log(title = "采购员查看所有订单", businessType = BusinessType.SELECT)
    @GetMapping("/listAll")
    public TableDataInfo listAll(String type, Long orderId, String materialTypeName, String state, int pageSize, int pageNum) {


        List<OrderDAO> list = orderService.selectList(type, orderId, materialTypeName, state);
//        List<OrderDAO> list1 = new ArrayList<>();
//        int pageNums = (pageNum - 1) , pagesize = (pageNum + 1) * pageSize;
//        System.out.println("size   " + pageSize + "     ：" + pageNums);
//        int size = list.size() > pagesize ? pagesize : list.size();
//        for (int k = pageNums; k < size; k++) {
//            list1.add(list1.get(k));
//        }
        return getDataTable(list);
    }

    @Log(title = "查看订单具体详细物资", businessType = BusinessType.SELECT)
    @GetMapping("/releaseMaterials")
    public AjaxResult releaseMaterialsList(Long orderId, String type) {
        if ("工程类".equals(type)) {
            return success(orderService.selectReleaseMaterialsListProject(orderId));
        } else {
            return success(orderService.selectReleaseMaterialsListOther(orderId));
        }
    }


    @Log(title = "删除订单", businessType = BusinessType.DELETE)
    @DeleteMapping
    public AjaxResult releaseMaterialsList(Long orderId) {
        orderService.deleteOrder(orderId);
        return success();
    }

    @Log(title = "查看订单供应商报价详情 ", businessType = BusinessType.SELECT)
    @GetMapping("/orderQuotation")
    public TableDataInfo orderQuotation(Long orderId) throws ParseException {
        startPage();
        OrderList orderList = orderMapper.selectOrder(orderId);
        if ("工程类".equals(orderList.getMaterialTypeName())) {
            return getDataTable(orderService.getQutationProjectInfo(orderList));
        } else {
            return getDataTable(orderService.getQutationOther(orderList));
        }
    }

    @Log(title = "询价单中标 ", businessType = BusinessType.INSERT)
    @PostMapping("/successBid")
    public AjaxResult successBid(Long orderId, Long supplierId) throws ServerException {
        orderService.successBid(orderId, supplierId);
        return success("中标完成");
    }

    //历史商品比价
    @PreAuthorize("@ss.hasPermi('purchase:purchase:insert')")
    @Log(title = "单个历史商品比价 ", businessType = BusinessType.INSERT)
    @GetMapping("/comparison")
    public TableDataInfo priceComparison(String name) throws ServerException {
        startPage();
        List<StoreQuotation> list = orderService.priceComparison(name);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('purchase:purchase:insert')")
    @Log(title = "采购员手商品类填订单 ", businessType = BusinessType.INSERT)
    @PostMapping("/storeOrder")
    public AjaxResult addStoreOrder(@RequestBody OrderVO orderVO) throws ServerException, ParseException {
        orderService.addStoreOrder(orderVO);
        return success();
    }

    @PreAuthorize("@ss.hasPermi('purchase:purchase:insert')")
    @Log(title = "采购员手填工程类订单 ", businessType = BusinessType.INSERT)
    @PostMapping("/projectOrder")
    public AjaxResult addProjectOrder(@RequestBody OrderVO orderVO) throws ServerException, ParseException {
        orderService.addProjectOrder(orderVO);
        return success();
    }

    @Log(title = "采购员确认收到货 ", businessType = BusinessType.INSERT)
    @GetMapping("/deliverygoods")
    public AjaxResult deliveryOfGoods(Long orderId) throws ServerException, ParseException {
        orderService.deliveryOfGoods(orderId);
        return success();
    }


    @Log(title = "采购员可查看某一订单未报价状态的供应商", businessType = BusinessType.SELECT)
    @GetMapping("/falseSupplier")
    public TableDataInfo falseSupplier(Long orderId, String state) throws ServerException {
        startPage();
        List<SysSupplierState> list = orderService.selectStateList(orderId, state);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('purchase:purchase:insert')")
    @Log(title = "导入预订单 查询最低价格", businessType = BusinessType.SELECT)
    @PostMapping("/up/lowestprice")
    public AjaxResult lowPrice(HttpServletResponse response, MultipartFile file) throws IOException {
        return success(orderService.historyList(response, file));
    }

    @PreAuthorize("@ss.hasPermi('purchase:purchase:insert')")
    @Log(title = "提醒供应商报价", businessType = BusinessType.SELECT)
    @GetMapping("/remind")
    public AjaxResult remind(String supplierId) throws IOException {
        orderService.remind(supplierId);
        return success();
    }

    //------------------------------------------------------------------------------------------------------------------------

    @PreAuthorize("@ss.hasPermi('supplier:supplier:supplier')")
    @Log(title = "供应商查看发布的订单", businessType = BusinessType.SELECT)
    @GetMapping("/bidList")
    public TableDataInfo bidList(String type, int pageSize, int pageNum ) throws ParseException {
        startPage();
        List<OrderList> list = orderService.bidList(type);
        List<OrderList> list1 = new ArrayList<>();

        int pageNums = (pageNum - 1) , pagesize = (pageNums + 1) * pageSize;

        int size = list.size() > pagesize ? pagesize : list.size();
        for (int k = pageNums; k < size; k++) {
            list1.add(list.get(k));
        }
        return getDataTable1(list1,list.size());
    }

    @PreAuthorize("@ss.hasPermi('supplier:supplier:supplier')")
    @Log(title = "供应商删除上传的询价单", businessType = BusinessType.DELETE)
    @DeleteMapping("/supplier")
    public AjaxResult deleteQuotation(Long orderId, String type) throws ServerException {
        orderService.deleteQutation(orderId, type);
        return success();
    }

    @PreAuthorize("@ss.hasPermi('supplier:supplier:supplier')")
    @Log(title = "供应商查看历史填写的询价单", businessType = BusinessType.SELECT)
    @GetMapping("/allquotation")
    public TableDataInfo allQuotation(String orderName, Long orderId) {
        startPage();
        List<OrderAllQuotationVO> list = orderService.allQuotation(orderName, orderId);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('supplier:supplier:supplier')")
    @Log(title = "供应商手动上传商品类订单", businessType = BusinessType.DELETE)
    @PostMapping("/supplier/addStore")
    public AjaxResult bidLi11st(@RequestBody OrderQuotationVO orderQuotationVO, MultipartFile photo) throws IOException, InvalidExtensionException {
        orderService.insertSupplierAddstore(orderQuotationVO);
        return success();
    }

    @PreAuthorize("@ss.hasPermi('supplier:supplier:supplier')")
    @Log(title = "供应商手动上传工程类订单", businessType = BusinessType.DELETE)
    @PostMapping("/supplier/addProject")
    public AjaxResult bidLis11t(@RequestBody OrderQuotationVO orderQuotationVO) throws IOException, InvalidExtensionException {
        return success(orderService.insertSupplierAddProject(orderQuotationVO));
    }


    @Log(title = "外部链接", businessType = BusinessType.DELETE)
    @PostMapping("/waibuUrl")
    public AjaxResult waibuUrl(Long orderId) throws IOException, InvalidExtensionException {
        return success(orderService.waibuUrl(orderId));
    }


    @GetMapping("/falseSuppliersswsss")
    public AjaxResult bidLis11t11() throws IOException, InvalidExtensionException {
        Long orderId = Long.valueOf("23072641683367");
        return success(orderService.waibuUrl(orderId));
    }
//        Long orderId = Long.valueOf("1230");
//        String url = "http://10.255.15.180:8020/msgIndex"+"?orderId="+orderId ;
//        return success(url);
    //orderService.test();
//        HashMap<String,String> map = new HashMap<>();
//        List<String[]> dynDataList = new ArrayList<>();
//        String[] dynData1 = new String[]{"手机号码","name","order"};
//        String[] dynData2 = new String[]{"15267679674","球球","外包订单"};
//        dynDataList.add(dynData1);
//        dynDataList.add(dynData2);
//        map.put("templateId","2261012056607");//模板ID
//        map.put("serialNumber","001");//流水号
//        map.put("dynData",dynDataList.toString());//动态数据
//        map.put("signCode","6710fea8-016c-4844-82bb-f102860f794f");//签名
//
////        String josnData;
//        String result = sendPostByForm("https://api.ums86.com/api/sms-var/send",map,0);
//        System.out.println(result);


//        String titles = "手机号码,name,order";
//        //参数变量名
//        String[] titleArr = titles.split(",");
//        //参数变量值
//        String datas = "15267679674,球球,外包订单";
//        String[] rows = datas.split(";");
//        String[][] dyns = new String[rows.length+1][titleArr.length];
//        dyns[0] = titleArr;
//        int rowNum = 1;
//        for(String row:rows){
//            String[] cols = row.split(",");
//            dyns[rowNum++] = cols;
//        }
//        //请求参数
//        DynSMSSendRequest sendRequest = new DynSMSSendRequest();
//        //模板ID
//        sendRequest.setTemplateId("2261012056607");
//        sendRequest.setDynData(dyns);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//        Random rd = new Random();
//        int seq = rd.nextInt(900000) + 100000;
//        //流水号,状态回执报告中一致.如果不需要状态回执报告请不要设置值
//        sendRequest.setSerialNumber(sdf.format(new Date()) + seq);
//        SDKApi sdkApi = null;
//        String spCode ="272939";
//        String appkey = "yg_cgxt";
//        String appSecret = "69261ed2657bacef24d031474b0441f8";
//
//        ApiConfig config = new ApiConfig(spCode, appkey, appSecret);
//        sdkApi = new SDKApi(config);
//        ComResult<DynSMSSendDataResult> result = sdkApi.testDynSendMethod(sendRequest);
//        System.out.println("--!" + result);
//        System.out.println("--!" + (result.isSucc()));
//        Assert.assertTrue(result.isSucc(), "动态发送结果");
//        return success();
//    }

    public void testDynSendMethod(String titles, String datas, String templateId) {

        //参数变量名
        String[] titleArr = titles.split(",");
        //参数变量值
        String[] rows = datas.split(";");
        String[][] dyns = new String[rows.length + 1][titleArr.length];
        dyns[0] = titleArr;
        int rowNum = 1;
        for (String row : rows) {
            String[] cols = row.split(",");
            dyns[rowNum++] = cols;
        }
        //请求参数
        DynSMSSendRequest sendRequest = new DynSMSSendRequest();
        //模板ID
        sendRequest.setTemplateId(templateId);
        sendRequest.setDynData(dyns);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Random rd = new Random();
        int seq = rd.nextInt(900000) + 100000;
        //流水号,状态回执报告中一致.如果不需要状态回执报告请不要设置值
        sendRequest.setSerialNumber(sdf.format(new Date()) + seq);
        SDKApi sdkApi = null;
        String spCode = "272939";
        String appkey = "yg_cgxt";
        String appSecret = "69261ed2657bacef24d031474b0441f8";

        ApiConfig config = new ApiConfig(spCode, appkey, appSecret);
        sdkApi = new SDKApi(config);
        ComResult<DynSMSSendDataResult> result = sdkApi.testDynSendMethod(sendRequest);
        Assert.assertTrue(result.isSucc(), "动态发送结果");
    }


}
